<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Model\Category;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Goods;
use App\Model\Links;
use Session,View,Cache,DB;

class CommonController extends Controller
{
    // 初始化获取公共信息
    public function __construct() {
        // 公共导航
        if(Cache::has('navs')){
            $navs = Cache::get('navs');
            $navGoods = Cache::get('navGoods');
        } else {
            $navs = Category::navs();
            $navGoods = [];
            foreach ($navs as $nav){
                $navGoods[$nav->id] = self::getNavsGoods($nav->id, 8);
                $nav->navGoods = $navGoods[$nav->id];
            }
            Cache::put('navs', $navs, 5);
            Cache::put('navGoods', $navGoods, 5);
        }
        
        $bottomLinks = self::getBottomLinks();
        $bottomFaqs = self::getBottomFaq();

        // 发送数据到视图
        View::share('navs', $navs);
        View::share('navGoods', $navGoods);
        View::share('bottomLinks', $bottomLinks);
        View::share('bottomFaqs', $bottomFaqs);
        
        if(method_exists($this, '__init')){
            $this->__init();
        }
    }
    
    // 验证用户是否登录
    protected function isLogin()
    {
        if(Session::has('userData')){
            return true;
        } else {
            return false;
        }
    }
    
    // 获取导航分类商品
    protected static function getNavsGoods($id)
    {
        $items = Goods::GoodsList($id, 8);
        return $items;
    }
    
    // 获取底部友情链接
    protected static function getBottomLinks()
    {
        $bottomLinks = Links::bottomLinks();
        return $bottomLinks;
    }
    
    // 获取底部帮助中心
    protected static function getBottomFaq()
    {
        if(!Cache::has('FAQ')){
            $faq = DB::table('faq');
            $cates = DB::table('faq_category')->where('cate_status', 1)
                    ->limit(4)
                    ->get();
            foreach($cates as $cate){
                $cate->faqs = $faq->where('pid', $cate->id)
                        ->limit(5)
                        ->select(['faq_title', 'id'])
                        ->get();
            }
//            Cache::forever('FAQ', $cates);
            return $cates;
        } else {
            return Cache::get('FAQ');
        }
    }
}
